package stackandqueue.queue.linkedqueue;

import stackandqueue.queue.inter.Queue;

public class LinkedQueue<T> implements Queue<T> {
    private QueueNode<T> front;
    private QueueNode<T> rear;
    private int queueLength = 0;

    public LinkedQueue() {
        front = new QueueNode<>();
        rear = new QueueNode<>();
        front.setNext(rear);
    }

    @Override
    public void clearQueue() {
        front.setNext(rear);
        queueLength = 0;
    }

    @Override
    public boolean queueEmpty() {
        return front.getNext() == rear;
    }

    @Override
    public T getHead() {
        return front.getNext().getData();
    }

    @Override
    public void enQueue(T e) {
        QueueNode<T> temp = new QueueNode<>(e, rear);
        QueueNode<T> p = front;
        while (p.getNext() != rear) {
            p = p.getNext();
        }
        p.setNext(temp);
    }

    @Override
    public T deQueue() {
        QueueNode<T> temp = front.getNext();
        if (temp != rear) {
            front.setNext(front.getNext().getNext());
        }
        return temp.getData();
    }

    @Override
    public int queueLength() {
        QueueNode<T> p = front;
        int i = 0;
        while ((p = p.getNext()) != rear) {
            i++;
        }
        return i;
    }
}
